﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEditor;

public class TestWindow : EditorWindow {
    public TimeLineObj timelineObj;

	[MenuItem("Test/TimeLine")]
    public static void ShowWindow()
    {
        GetWindow<TestWindow>(false, "Test", true);
    }
    //TODO: scrollView 支持长度超过10s 
    //滚动条: 只是第二段track 滚动 ScrollView Vertical   Frame Horizontal 滚动
    void OnGUI()
    {
        #region Init
        if (timelineObj == null)
        {
            var go = GameObject.Find("TimeLineObj");
            if (go)
            {
                timelineObj = go.GetComponent<TimeLineObj>();
            }
            if (!timelineObj)
            {
                MessageBox("创建一个TimeLineObj", MessageBoxType.Info);
                if (GUILayout.Button("Add Component"))
                {
                    if (!go) go = new GameObject("TimeLineObj");
                    go.AddComponent<TimeLineObj>();
                }
                return;
            }
        }
        #endregion

        GUI.DrawTexture(new Rect(0f, 0f, position.width, height_menu_bar - 2f), EditorStyles.toolbar.normal.background);
        //EditorGUILayout.BeginVertical(GUILayout.MinHeight(50), GUILayout.Height(50));

        #region FrameNumber
        var startKey = 0;
        var initPos = frameInitPos;
        var offX = -scrollViewValue.x;
        var startPos = initPos;
        var endPos = position.width-5f;

        for (var i = startKey; i < timelineObj.totalTime+1; i++)
        {
            float newKeyNumberX = initPos + width_second * i + 2f;
            var realPos = newKeyNumberX + offX;
            if (realPos > startPos && realPos < endPos)
            {
                var rectKeyNumber = new Rect(realPos, 2f, GUI.skin.label.CalcSize(new GUIContent(i.ToString())).x, height_menu_bar);
                GUI.Label(rectKeyNumber, i.ToString());
            }

            var initKeDu = initPos + width_second * i + width_second / 5;
            var offKeDu = width_second / 5;
            for(var j = 0; j < 4; j++)
            {
                var keX = initKeDu + offKeDu * j;
                var realPos2 = keX + offX;
                if (realPos2 > startPos && realPos2 < endPos)
                {
                    var rectKeDu = new Rect(realPos2, 2f, offKeDu, height_menu_bar);
                    GUI.Label(rectKeDu, "|");
                }
            }
        }
        #endregion


        #region Tracks
        height_all_tracks = timelineObj.channels.Count * height_track + 50f;
        //Debug.LogError("AllTrack:"+height_all_tracks);
        //float height_scrollview = position.height - ( height_menu_bar);

        //var scrollWidth = Mathf.Max(position.width, timelineObj.totalTime * width_second+frameInitPos);
        //Rect rectScrollView = new Rect(0f,  height_menu_bar + 2f, position.width, height_scrollview);

        EditorGUILayout.BeginVertical(GUILayout.MinHeight(50), GUILayout.Height(height_menu_bar+2));
        EditorGUILayout.Space();
        EditorGUILayout.EndVertical();

        scrollViewValue = EditorGUILayout.BeginScrollView(scrollViewValue, true, true);
        //Debug.LogError("scrollViewValue:"+scrollViewValue);

        Vector2 scrollViewBounds = new Vector2(scrollViewValue.y, scrollViewValue.y + height_all_tracks);

        frame_total_length = (timelineObj.totalTime + 1) * width_second + frameInitPos;

        //EditorGUILayout.BeginHorizontal(GUILayout.Height(height_all_tracks), GUILayout.Width(frameLength));
        //EditorGUILayout.BeginVertical(GUILayout.Height(height_track));
      
            float track_y = 2f;		// the next track's y position
        //var track_y = 0.0f;
            // tracks vertical start
            for (int i = 0; i < timelineObj.channels.Count; i++)
            {
                if (track_y > scrollViewBounds.y) break;	// if start y is beyond max y
                var channel = timelineObj.channels[i];
                float height_group_elements = 0f;

                //GUI.DrawTexture(new Rect(0f, track_y-4f, position.width, height_track+8f), EditorStyles.toolbar.normal.background);
                showGroupElement(channel, 0, ref track_y, ref height_group_elements, scrollViewBounds);
            } 
            //EditorGUILayout.EndVertical();
        //EditorGUILayout.EndHorizontal();
            
        EditorGUILayout.EndScrollView();

        #endregion

    }

    //每行 两列
    bool showGroupElement(StoryChannel channel, int group_lvl, ref float track_y, ref float height_group_elements, Vector2 scrollViewBounds)
    {
        return showTrack(channel, group_lvl, ref track_y, ref height_group_elements, scrollViewBounds);
    }

    bool showTrack(StoryChannel channel, int group_level, ref float track_y, ref float height_group_elements, Vector2 scrollViewBounds)
    {
        /*
        //超过Y边界不要绘制
        if ((track_y + height_track) < scrollViewBounds.x || track_y > scrollViewBounds.y)
        {
            track_y += height_track;
            return false;
        }
        */
        EditorGUILayout.BeginHorizontal(GUILayout.Width(frame_total_length), GUILayout.Height(height_track+5));
        EditorGUILayout.Space();
        EditorGUILayout.EndHorizontal();
        float track_x = 0;
        Rect rectTrack = new Rect(track_x+2f, track_y, width_track - track_x-2f, height_track-2);
        if (GUI.Button(rectTrack, channel.name))
        {
            Selection.activeGameObject = channel.gameObject;
        }
        var initX = frameInitPos;
        var offX = width_second;
        var actions = channel.actions;
        for(var i = 0; i < actions.Count; i++)
        {
            var act = actions[i];
            var sp = act.startTime * offX + initX;
            var ep = act.endTime * offX + initX;
            var rect2 = new Rect(sp, track_y, ep-sp, height_track-2);
            if(GUI.Button(rect2, act.name))
            {
                Selection.activeGameObject = act.gameObject; 
            }
        }

        track_y += height_track+4;

        return true;
    }

    public static void MessageBox(string message, MessageBoxType type)
    {

        MessageType messageType;
        if (type == MessageBoxType.Error) messageType = MessageType.Error;
        else if (type == MessageBoxType.Warning) messageType = MessageType.Warning;
        else messageType = MessageType.Info;

        EditorGUILayout.HelpBox(message, messageType);
    }


    public enum MessageBoxType
    {
        Info = 0,
        Warning = 1,
        Error = 2
    }

    private float height_menu_bar = /*30f*/20f;
    private float height_all_tracks;
    private float height_track = 58;
    private Vector2 scrollViewValue;
    private float width_track = 150f;
    private float width_second = 100;
    private float frameInitPos = 155;
    private float frame_total_length = 150;
}
